﻿package work.tools.deadline
{
	import flash.net.SharedObject;
	
	/**
	 * 期限类 
	 * @author zhangfeng
	 * 
	 */
	public class Deadline
	{
		
		private var so:SharedObject;
		private var qualificationGroups:QualificationGroups;
		/**
		 * 期限类
		 * @param date 起始时间
		 * @see IQualification
		 */
		public function Deadline(date:Date=null)
		{
			qualificationGroups=new QualificationGroups(date);
			try
			{
				so=SharedObject.getLocal("Deadline");
				if(date)
				{
					startDate=date;
				}
				
				if(!so.data.openCount)
				{
					so.data.openCount=1;
				}else
				{
					so.data.openCount++;
				}
				
				so.flush();
				qualificationGroups.openCount=so.data.openCount;
				qualificationGroups.startDate=so.data.startDate;
				if(so.data.isPass)
				{
					addError();
					return;
				}
			}catch(e:Error)
			{
				throw new Error(e);
				qualificationGroups.openCount=1;
			}
			
		}

		/**
		 * 起始时间,只能设置一次
		 * @return 
		 * 
		 */
		public function get startDate():Date
		{
			return qualificationGroups.startDate;
		}

		public function set startDate(value:Date):void
		{
			if(qualificationGroups.startDate != value)
			{
				if(!so.data.startDate)
				{
					qualificationGroups.startDate=value;
					so.data.startDate=value;
				}
			}
		}
		
		/**
		 * 是否过期 
		 * @return 
		 * 
		 */
		public function isPass():Boolean
		{
			if(so.data.isPass)
			{
				addError();
				return true;
			}
			var bool:Boolean=qualificationGroups.isPass();
			if(bool)
			{
				addError();
			}
			return bool;
		}
		/**
		 * 获得剩余的期限天数 
		 * @return 如果返回正数，表示还有几天过期，如果返回负数，表示已经过期了几天
		 * 
		 */
		public function getSurplus():Number
		{
			if(so.data.isPass)
			{
				addError();
				return -10000;
			}
			var num:Number=qualificationGroups.getSurplus();
			if(num<0)
			{
				addError();
			}
			return num;
		}
		
		private function addError():void
		{
			//throw new Error("授权已过期！");
			so.data.isPass=true;
			so.flush();
			//throw new Error("Your license has expired, Please contact manufacturer.");
		}
		
		public function showError():void
		{
			addError();
			throw new Error("Your license has expired, Please contact manufacturer.");
		}
		
		/**
		 * 添加一个期限条件 
		 * @param qualification 条件
		 * @see IQualification
		 */
		public function addQualification(qualification:IQualification):void
		{
			qualificationGroups.addQulification(qualification);
		}
		
		/**
		 * 删除一个期限条件 
		 * @param className 期限条件类名
		 * @return 如果有返回这个期限条件，否则返回null
		 * 
		 */
		public function removeQualification(className:String):IQualification
		{
			return qualificationGroups.removeQulification(className);
		}
		/**
		 * 删除所有期限条件 
		 * 
		 */
		public function removeAllQualification():void
		{
			qualificationGroups.removeAllQulification();
		}
		
	}
}